import { Button, Col, DatePicker, Form, Input, message, Modal, Row, Select, Table } from 'antd';
import { ColumnsType } from 'antd/lib/table';
import moment from 'moment';
import { checkPermission } from 'permission/Index';
import React, { RefObject } from 'react';
import { JSONObject } from 'admin/schema/common';
import { CallTaskCountMsg } from 'admin/schema/SocketMessage';
import { HandleColInfo, TaskInfo, TaskStatus } from 'admin/schema/Task';
import {
  createTaskListDownloadTask,
  delTask,
  getCallTaskCol,
  getTaskList,
  modifyCallTaskCol,
  startTask,
  stopTask,
} from 'admin/servers/servers';
import { getSocket } from 'servers/socket';
import { clearNull, deleteRowChangePageNum, getTableIndex, toPercent } from 'utils/tools';
import CallTaskOperation from './components/CallTaskOperation';
import './style.scss';
import {
  flowTypeOption,
  getFlowTypeName,
  getStatusName,
  getTaskProcessDom,
  taskStatusOption,
} from '../components/TaskTool';
import { CustomCol } from '../components/CustomCol';
import CallRepeatPop from './components/CallRepeatPop';
import DownloadModel from 'admin/components/DownloadModel';

const { RangePicker } = DatePicker;
interface CallTaskState {
  taskName: string;
  flowType: number;
  taskStatus: TaskStatus;
  beginTime: string;
  endTime: string;
  /** table列头 */
  tableColumns: ColumnsType<TaskInfo>;
  /** 定制列应用的结构 */
  customCol: HandleColInfo[];
  tableData: TaskInfo[];
  repeatTaskId?: number;
  // 分页相关数据
  pageInfo: {
    pageTotal: number;
    pageNum: number;
    pageSize: number;
  };
  tableLoading: boolean;
  showRepeatPop: boolean;
  addTaskModalVisible: boolean;
  showDownload: boolean;
}
/** 任务管理-外呼任务列表 */
class CallTask extends React.Component<{}, CallTaskState> {
  /**定制列 */
  private customColRef: React.RefObject<CustomCol>;
  constructor(prop: {}) {
    super(prop);
    this.customColRef = React.createRef();
    this.state = {
      taskName: '',
      flowType: -1,
      taskStatus: 0,
      beginTime: '',
      endTime: '',
      customCol: [],
      tableColumns: [],
      tableData: [],
      repeatTaskId: undefined,
      pageInfo: {
        pageTotal: 0,
        pageNum: 1,
        pageSize: 10,
      },
      tableLoading: false,
      showRepeatPop: false,
      addTaskModalVisible: false,
      showDownload: false,
    };
  }

  componentDidMount() {
    this.addSocketEvent();
    this.fetchCol();
    this.fetchList();
  }
  componentWillUnmount = () => {
    this.removeSocketEvent();
    this.setState = (state, callback) => {
      return;
    };
  };
  /* 自定义-列渲染-【任务列表定制列】*/
  private renderTableCols(item: any) {
    const obj = {
      title: item.desc,
      key: item.columnName,
      dataIndex: item.columnName,
      ellipsis: true,
      render: (text: any, record: TaskInfo, index: number) => {
        return text;
      },
    };
    // 前端显示（特殊列-处理）
    switch (item.columnName) {
      case 'flowType': // 任务类型
        obj.render = text => getFlowTypeName(text);
        break;
      case 'taskStatus': // 任务状态
        obj.render = text => getStatusName(text);
        break;
      case 'blackSwitch': // 黑名单开关
        obj.render = text => (text ? '开启' : '关闭');
        break;
      case 'finishedTaskNum': // 任务进度条展示
        obj.render = (text: any, record: TaskInfo) => getTaskProcessDom(record);
        break;
      case 'startMode':
        obj.render = text => (text ? '手动启动' : '自动启动');
        break;
      case 'connectRate': // 接通率等
      case 'callLossRate':
      case 'transferManualRate':
      case 'transferManualCallLossRate':
      case 'transferManualConnectRate':
        obj.render = (text: any, record: TaskInfo) => toPercent(text);
        break;
      default:
        break;
    }
    return obj;
  }

  /**
   * 获取列头信息
   */
  private async fetchCol() {
    try {
      const res = await getCallTaskCol();
      /**后端返回的table列头信息，包含switch信息 */
      const originData = res.data;
      /**定制列信息 */
      const custom_cols: HandleColInfo[] = [];
      /**表格列 */
      const table_cols: ColumnsType<TaskInfo> = [];
      // 遍历列数据
      const arr = [
        '转人工数',
        '转人工率',
        '转人工接起量',
        '转人工接起率',
        '转人工呼损量',
        '转人工呼损率',
      ];
      originData
        .filter(({ desc }) => !arr.includes(desc))
        .forEach((item, index) => {
          // console.log("原始-列信息-", item);
          item.desc = item.desc ? item.desc : '列-' + item.columnName;
          // 定制列，存储所有列
          custom_cols.push({
            title: item.desc,
            key: item.columnName,
            switch: item.switch,
          });
          // table，只查找为on的列，存入table列展示
          if (!item.switch || item.switch !== 'on') {
            return;
          }
          const obj = this.renderTableCols(item);
          table_cols.push(obj);
        });
      /**表格第一列：序号列 */
      const index_col: any = {
        title: '序号',
        key: 'index',
        dataIndex: 'index',
        fixed: 'left',
        width: 70,
        render: (text: any, record: TaskInfo, index: number) =>
          getTableIndex(index, this.state.pageInfo.pageSize, this.state.pageInfo.pageNum),
      };
      /**表格最后一列：操作列 */
      const operation_col = {
        title: '操作',
        key: 'opearation',
        fixed: 'right',
        width: 260,
        render: (text: any, record: TaskInfo) => {
          return (
            <>
              <Button
                type="link"
                onClick={() => {
                  this.jumpToDetail(record.taskId);
                }}
              >
                详情
              </Button>
              {checkPermission('/task/callTask/repeat') && (
                <Button
                  type="link"
                  onClick={() => {
                    this.handleRepeatTask(record.taskId);
                  }}
                  disabled={!record.allowRepeatCall}
                >
                  重呼
                </Button>
              )}
              {checkPermission('/task/callTask/delete') && (
                <Button
                  type="link"
                  onClick={() => {
                    this.deleteTask(record.taskId);
                  }}
                >
                  删除
                </Button>
              )}
              {(record.taskStatus === TaskStatus.IN_HANDLE ||
                record.taskStatus === TaskStatus.NO_CALL) &&
                checkPermission('/task/callTask/pause') && (
                  <Button
                    type="link"
                    onClick={() => {
                      this.handleStopTask(record.taskId);
                    }}
                  >
                    暂停
                  </Button>
                )}
              {(record.taskStatus === TaskStatus.HAD_STOP ||
                (record.taskStatus === TaskStatus.NOT_HANDLE && record.startMode === 1)) &&
                checkPermission('/task/callTask/start') && (
                  <Button
                    type="link"
                    onClick={() => {
                      this.handleStartTask(record.taskId);
                    }}
                  >
                    启动
                  </Button>
                )}
            </>
          );
        },
      };
      /**数据源：表格列;switch为on，包含，序号，操作列 */
      const table_columns: any = [index_col, ...table_cols, operation_col];
      console.log('table_columns', table_columns);
      this.setState({
        customCol: custom_cols,
        tableColumns: table_columns,
      });
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
  }
  /**
   * 刷新数据
   */
  private async fetchList() {
    this.setState({
      tableLoading: true,
    });
    const { taskName, taskStatus, flowType, beginTime, endTime, pageInfo } = this.state;
    const { pageNum, pageSize } = pageInfo;
    try {
      const { count, data } = await getTaskList(
        clearNull({
          taskName: taskName,
          flowType: flowType >= 0 ? flowType : '',
          taskStatus: taskStatus > 0 ? taskStatus : '',
          beginTime: beginTime,
          endTime: endTime,
          pageNo: pageNum,
          pageSize: pageSize,
        })
      );
      // 新的翻页信息
      pageInfo.pageTotal = count || 0;
      this.setState({
        tableData: data || [],
        pageInfo: pageInfo,
      });
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
    this.setState({
      tableLoading: false,
    });
  }

  /**
   * 绑定socket事件
   */
  private addSocketEvent() {
    console.log('任务列表推送-socket事件-start');
    getSocket().addEvent('callTaskStatusBroadcastEvent', (data: JSONObject) => {
      setTimeout(() => {
        // console.log(data, '推送-任务列表-任务进度更新');
        data = data as CallTaskCountMsg;
        const copyTableData = this.state.tableData;
        const aim = copyTableData?.find((item: any) => item.taskId.toString() === data.taskId);
        if (aim) {
          // 任务进度
          // console.log(aim, "进度");
          // 推送有状态，才开始更新状态
          if (data.taskStatus) {
            aim.taskStatus = data.taskStatus;
          }
          aim.totalTaskNum = data.countTotal;
          aim.finishedTaskNum = data.countComplete;
          this.setState({
            tableData: copyTableData,
          });
        }
      }, 0);
    });
  }

  /** 卸载socket事件*/
  private removeSocketEvent() {
    console.log('任务列表推送->>>>socket事件-删除');
    const socket = getSocket();
    socket.removeEvent(['callTaskStatusBroadcastEvent']);
  }

  /**
   * 暂停任务
   */
  private handleStopTask(taskId: number) {
    stopTask(taskId)
      .then(res => {
        message.success('暂停成功');
        this.fetchList();
      })
      .catch(error => {
        console.error(`系统异常: ${JSON.stringify(error)}`);
      });
  }

  /**
   * 启动任务
   */
  private handleStartTask(taskId: number) {
    startTask(taskId)
      .then(res => {
        message.success('启动成功');
        this.fetchList();
      })
      .catch(error => {
        console.error(`系统异常: ${JSON.stringify(error)}`);
      });
  }

  /**
   * @private 绑定onChange事件：时间范围选择器
   * @param {*} dates moment格式
   * @param {*} dateStrings dateFormate格式
   * @memberof CallTask
   */
  private onDateChange(dates: any, dateStrings: any) {
    console.log(dates, '选择的日期范围', dateStrings);
    this.setState({
      beginTime: dateStrings[0],
      endTime: dateStrings[1],
    });
  }

  /**
   * 删除表格行数据后，当前页刷新
   * @param size 条数
   */
  private freshTableDelRow(size: number) {
    const { pageTotal, pageNum, pageSize } = this.state.pageInfo;
    const newPageNum = deleteRowChangePageNum(size, pageTotal, pageNum, pageSize);
    this.setState(
      {
        pageInfo: {
          pageTotal,
          pageSize,
          pageNum: newPageNum,
        },
      },
      () => {
        this.fetchList();
      }
    );
  }
  /**
   * 删除任务
   */
  private deleteTask(id: number) {
    Modal.confirm({
      content: '删除任务后无法恢复，确定删除吗',
      onOk: () => {
        delTask(id)
          .then(res => {
            message.success('删除成功');
            this.freshTableDelRow(1);
          })
          .catch(error => {
            console.error(`系统异常: ${JSON.stringify(error)}`);
          });
      },
    });
  }

  /**
   * 重呼任务
   */
  private handleRepeatTask(taskId: number) {
    this.setState({
      repeatTaskId: taskId,
      showRepeatPop: true,
    });
  }

  /**
   * 跳转至任务详情
   */
  private jumpToDetail = (id: number) => {
    (this.props as JSONObject).history.push('/webapp/outbound/task/callTask/detail?id=' + id);
  };

  /**
   * 重置搜索列表
   */
  private resetSearch() {
    // 重置搜索条件；重置列表
    this.setState({
      taskName: '',
      flowType: -1,
      taskStatus: 0,
      beginTime: '',
      endTime: '',
    });
    this.jumpPage(1);
  }

  /**
   * 跳页方法
   */
  private jumpPage(pageNum: number, pageSize?: number): void {
    const newProp = this.state.pageInfo;
    newProp.pageNum = pageNum;
    if (pageSize) {
      newProp.pageSize = pageSize;
    }
    this.setState(
      {
        pageInfo: newProp,
      },
      () => {
        this.fetchList();
      }
    );
  }
  /**
   * 打开定制列对话框
   */
  private handleColumn(): void {
    this.customColRef.current?.show();
    this.customColRef.current?.setCol(this.state.customCol);
  }
  /**
   * 根据搜索条件导出任务列表（在下载中心展示，需推送）
   */
  private async handleExport(): Promise<void> {
    // 创建下载任务
    const { taskName, taskStatus, flowType, beginTime, endTime } = this.state;
    try {
      const res = await createTaskListDownloadTask(
        clearNull({
          taskName: taskName,
          flowType: flowType >= 0 ? flowType : '',
          taskStatus: taskStatus > 0 ? taskStatus : '',
          beginTime: beginTime,
          endTime: endTime,
        })
      );
      if (res.code === 0) {
        // 创建下载任务
        message.warning('数据正在准备中，请稍候到下载管理中下载');
      } else {
        message.error(`${res.tips}(错误码:${res.code})`);
      }
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
  }

  /**操作：定制列-回调函数 */
  handleModifyColsCallFn = (res: any) => {
    modifyCallTaskCol(res)
      .then(response => {
        message.success('编辑成功');
        this.fetchCol();
      })
      .catch(error => {
        console.error(`系统异常: ${JSON.stringify(error)}`);
      });
  };
  /**操作：新建任务-回调函数 */
  handleAddCallTaskCallFn = (fresh?: boolean) => {
    this.setState({
      addTaskModalVisible: false,
    });
    if (fresh) {
      this.jumpPage(1);
    }
  };

  /**操作：重呼-回调函数 */
  handleRepeatCallCallFn = (obj: any) => {
    if (obj) {
      // 重呼-确定-返回-需更新列表
      this.fetchList();
    }
    // 关闭弹窗
    this.setState({
      showRepeatPop: false,
    });
  };

  /**
   * 控制头部icon抽屉，显示/隐藏
   */
  toggleShow = (str: string) => {
    console.log('🚀 ~ CallTask ~ str:', str);
    if (str === 'download') {
      // 打开-下载抽屉
      this.setState({
        showDownload: true,
      });
    } else {
      // 关闭-所有抽屉
      this.setState({
        showDownload: false,
      });
    }
  };

  render() {
    const {
      tableColumns,
      tableData,
      tableLoading,
      repeatTaskId,
      pageInfo: { pageNum, pageSize, pageTotal },
      taskName,
      taskStatus,
      flowType,
      beginTime,
      endTime,
      showRepeatPop,
      addTaskModalVisible,
      showDownload,
    } = this.state;

    const { customColRef } = this;
    const dateFormat = 'YYYY-MM-DD';

    return (
      <>
        <div className="mgr-header task-list-header">
          <div className="mgr-header-left">
            <Form>
              <Row gutter={24}>
                <Col md={12} xl={8} xxl={6}>
                  <Form.Item label="任务名称">
                    <Input
                      value={taskName}
                      placeholder="请输入任务名称"
                      onChange={e => {
                        this.setState({ taskName: e.target.value.trim() });
                      }}
                    />
                  </Form.Item>
                </Col>
                <Col md={12} xl={8} xxl={5}>
                  <Form.Item label="任务类型">
                    <Select
                      value={flowType}
                      options={flowTypeOption}
                      onChange={val => {
                        this.setState({ flowType: val });
                      }}
                    />
                  </Form.Item>
                </Col>
                <Col md={12} xl={8} xxl={5}>
                  <Form.Item label="任务状态">
                    <Select
                      value={taskStatus}
                      options={taskStatusOption}
                      onChange={val => {
                        this.setState({ taskStatus: val });
                      }}
                    />
                  </Form.Item>
                </Col>
                <Col md={12} xl={10} xxl={8}>
                  <Form.Item label="创建日期">
                    <RangePicker
                      value={
                        beginTime && endTime
                          ? [moment(beginTime, dateFormat), moment(endTime, dateFormat)]
                          : null
                      }
                      ranges={{
                        今天: [moment().startOf('day'), moment().endOf('day')],
                        本周: [moment().startOf('week'), moment().endOf('week')],
                        本月: [moment().startOf('month'), moment().endOf('month')],
                      }}
                      onChange={this.onDateChange.bind(this)}
                      allowClear
                    />
                  </Form.Item>
                </Col>
              </Row>
            </Form>
          </div>
          <div className="mgr-header-right">
            <Row justify="end">
              <Col>
                <Button
                  type="primary"
                  onClick={() => {
                    this.jumpPage(1);
                  }}
                >
                  搜索
                </Button>
                <Button
                  type="primary"
                  ghost
                  onClick={() => {
                    this.resetSearch();
                  }}
                >
                  重置
                </Button>
                {checkPermission('/task/callTask/add') && (
                  <Button
                    type="primary"
                    onClick={() => {
                      this.setState({
                        addTaskModalVisible: true,
                      });
                    }}
                  >
                    新建任务
                  </Button>
                )}
              </Col>
            </Row>
            <Row justify="end">
              <Col>
                <DownloadModel fn={this.toggleShow} visible={showDownload} />
                <Button
                  type="primary"
                  onClick={() => {
                    this.handleColumn();
                  }}
                >
                  定制列
                </Button>
                {checkPermission('/task/callTask/export') && (
                  <Button
                    type="primary"
                    onClick={() => {
                      this.handleExport();
                    }}
                  >
                    导出
                  </Button>
                )}
              </Col>
            </Row>
          </div>
        </div>
        <div className="mgr-table">
          <Table
            loading={tableLoading}
            dataSource={tableData}
            scroll={{ x: 'max-content' }}
            columns={tableColumns}
            rowKey="taskId"
            pagination={{
              showSizeChanger: true,
              total: pageTotal,
              showTotal: total => `共 ${total} 条`,
              current: pageNum,
              pageSize: pageSize,
              onChange: (pageNum, pageSize) => {
                this.jumpPage(pageNum, pageSize as number);
              },
            }}
          />
        </div>
        <CallRepeatPop
          taskId={repeatTaskId as number}
          show={showRepeatPop}
          callBack={this.handleRepeatCallCallFn}
        />
        {addTaskModalVisible && (
          <CallTaskOperation
            visible={addTaskModalVisible}
            callback={this.handleAddCallTaskCallFn}
          />
        )}
        <CustomCol ref={customColRef} callback={this.handleModifyColsCallFn} />
      </>
    );
  }
}

export default CallTask;
